package com.qf.openapi.web.master.controller;


import com.qf.openapi.web.master.utils.Constants;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Controller
public class DownloadController {

    @GetMapping("/download")
    public void download(String filename, HttpServletResponse resp, HttpServletRequest req) throws IOException {
        
        //1.根据文件名找到文件，把文件内容写回response对象的输出流中
        String realPath = req.getServletContext().getRealPath(Constants.UPLOAD_PATH);
    
        String finalFilePath = realPath + File.separator + filename;
        
        //2.添加文件下载响应头
        resp.setHeader("content-disposition", "attachment;filename=" + filename);
    
        IOUtils.copy(Files.newInputStream(Paths.get(finalFilePath)), resp.getOutputStream());
    }
}
